// 根据类别id查询类别详情
export const loadCategoryById = (categoryId) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: `${getBaseUrl()}/chapter/getChapterById/${categoryId}`, // 假设后端有对应根据id获取类别的接口地址，这里需要替换成真实的后端接口地址
            method: 'GET',
            success: (res) => {
                if (res.data.code === 200) {
                    resolve(res.data.data); // 成功则返回后端数据中的实际数据部分（对应单个类别详情对象）
                } else {
                    reject(new Error('获取类别详情数据失败'));
                }
            },
            fail: (err) => {
                reject(err);
            }
        });
    });
}

// 加载所有类别
export const loadCategories = () => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: `${getBaseUrl()}/chapter/getAllChapter`, // 后端接口地址
            method: 'GET',
            success: (res) => {
                if (res.data.code === 200) {
                    resolve(res.data.data); // 成功则返回后端数据中的实际数据部分
                } else {
                    reject(new Error('获取类别数据失败'));
                }
            },
            fail: (err) => {
                reject(err);
            }
        });
    });
}
// 根据章节id获取对应题目列表
export const loadQuestionByChapterId = (chapterId) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: `${getBaseUrl()}/question/getQuestionByChapterId/${chapterId}`, // 后端接口地址，根据章节id拼接路径
            method: 'GET',
            success: (res) => {
                if (res.data.code === 200) {
                    resolve(res.data.data); // 成功则返回后端数据中的实际数据部分
                } else {
                    reject(new Error('获取题目数据失败'));
                }
            },
            fail: (err) => {
                reject(err);
            }
        });
    });
}

import { getBaseUrl } from '../config'

/**
 * 发送验证码
 * @param {Object} data - 请求数据
 * @param {string} data.phone - 手机号
 * @returns {Promise} - 返回Promise对象
 */
export const sendVerificationCode = (data) => {
  return request({
    url: `${getBaseUrl()}/user/verification/code/send`,
    method: 'POST',
    data
  })
}

/**
 * 用户登录/注册
 * @param {Object} data - 请求数据
 * @param {string} data.phone - 手机号
 * @param {string} [data.code] - 验证码(type=1时必填)
 * @param {string} [data.password] - 密码(type=2时必填)
 * @param {number} data.type - 登录类型(1-验证码登录,2-密码登录)
 * @returns {Promise} - 返回Promise对象
 */
export const userLogin = (data) => {
  return request({
    url: `${getBaseUrl()}/user/login`,
    method: 'POST',
    data
  })
}

/**
 * 封装uni.request
 * @param {Object} options - 请求配置
 * @returns {Promise} - 返回Promise对象
 */
function request(options, retryCount = 0, maxRetries = 2) {
  const timeout = 300000; // 5分钟超时
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      timeout: timeout, // 设置超时时间
      success: (res) => {
        if (res.data.code === 200) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      },
      fail: async (err) => {
        console.error(`请求失败 (尝试 ${retryCount + 1}/${maxRetries + 1}):`, err);
        
        if (retryCount < maxRetries) {
          // 延迟重试，每次重试增加延迟
          const delay = (retryCount + 1) * 2000;
          await new Promise(resolve => setTimeout(resolve, delay));
          
          try {
            const result = await request(options, retryCount + 1, maxRetries);
            resolve(result);
          } catch (retryErr) {
            reject(retryErr);
          }
        } else {
          reject(err);
        }
      }
    })
  })
}

/**
 * 用户退出登录
 * @returns {Promise} - 返回Promise对象
 */
export const userLogout = () => {
  return request({
    url: `${getBaseUrl()}/user/logout`,
    method: 'POST',
    header: {
      'Authorization': 'Bearer ' + uni.getStorageSync('token')
    }
  })
}

/**
 * 获取用户信息
 * @returns {Promise} - 返回Promise对象
 */
export const getUserInfo = () => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${getBaseUrl()}/user/getUserInfo`, // 假设的获取用户信息接口
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + uni.getStorageSync('token')
      },
      // 文件：service/api.js 中的 getUserInfo 函数
      success: (res) => {
        console.log('实际接收到的数据:', res.data); // 后端返回的完整数据
        let data;
        if (typeof res.data === 'string') {
          try {
            data = JSON.parse(res.data);
          } catch (err) {
            console.error('解析 JSON 数据失败:', err);
            reject(err);
            return;
          }
        } else {
          data = res.data; // data 应为后端返回的完整对象（包含 code、msg、data）
        }
        if (data.code === 200) { // 直接判断 data.code，而非 res.statusCode（HTTP 状态码）
          resolve(data.data); // 只返回数据体中的 data 字段
        } else {
          reject(new Error(data.msg || '获取用户信息失败'));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

export const submitAnswers = (data) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${getBaseUrl()}/question/answerUpload`,
      method: 'POST',
      data,
      header: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + uni.getStorageSync('token')
      },
      success: (res) => {
        if (res.data.code === 200) {
          resolve(res.data);
        } else {
          reject(new Error(res.data.message || '提交答案失败'));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

/**
 * 获取当天学习时间
 * @returns {Promise} - 返回Promise对象
 */
export const getTodayStudyTime = () => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${getBaseUrl()}/dailyStudy/todayStudyTime`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + uni.getStorageSync('token')
      },
      success: (res) => {
        if (res.data.code === 200) {
          resolve(res.data.data);
        } else {
          reject(new Error(res.data.message || '获取学习时间失败'));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

/**
 * 获取今日刷题数
 * @returns {Promise} - 返回Promise对象
 */
export const getTodayQuestionCount = () => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${getBaseUrl()}/question/userQuestionCount`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + uni.getStorageSync('token')
      },
      success: (res) => {
        console.log('实际接收到的数据:', res.data);
        if (res.data.code === 200) {
          resolve(res.data.data);
        } else {
          reject(new Error(res.data.message || '获取刷题数失败'));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

// 合并上传头像和背景图的接口
export const uploadFiles = async (avatarPath, backgroundImgPath) => {
    const result = {};

    if (avatarPath) {
        result.avatarUrl = await new Promise((resolve, reject) => {
            uni.uploadFile({
                url: `${getBaseUrl()}/user/uploadFiles`,
                filePath: avatarPath,
                name: 'avatar',
                header: {
                    'Authorization': 'Bearer ' + uni.getStorageSync('token')
                },
                success: (res) => {
                    const data = JSON.parse(res.data);
                    if (data.code === 200) {
                        resolve(data.data.avatarUrl);
                    } else {
                        reject(new Error(data.message || '头像上传失败'));
                    }
                },
                fail: (err) => {
                    reject(err);
                }
            });
        });
    }

    if (backgroundImgPath) {
        result.backgroundImgUrl = await new Promise((resolve, reject) => {
            uni.uploadFile({
                url: `${getBaseUrl()}/user/uploadFiles`,
                filePath: backgroundImgPath,
                name: 'backgroundImg',
                header: {
                    'Authorization': 'Bearer ' + uni.getStorageSync('token')
                },
                success: (res) => {
                    const data = JSON.parse(res.data);
                    if (data.code === 200) {
                        resolve(data.data.backgroundImgUrl);
                    } else {
                        reject(new Error(data.message || '背景图上传失败'));
                    }
                },
                fail: (err) => {
                    reject(err);
                }
            });
        });
    }

    return result;
};

// 更新用户信息接口
export const updateUserInfo = (data) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: `${getBaseUrl()}/user/update`,
            method: 'POST',
            header: {
                'Authorization': 'Bearer ' + uni.getStorageSync('token'),
                'Content-Type': 'application/json'
            },
            data: data,
            success: (res) => {
                if (typeof res.data === 'string') {
                    const data = JSON.parse(res.data);
                    if (res.statusCode === 200 && data.code === 200) {
                        resolve(data.data);
                    } else {
                        reject(new Error(data.message || '更新用户信息失败'));
                    }
                } else {
                    if (res.statusCode === 200 && res.data.code === 200) {
                        resolve(res.data.data);
                    } else {
                        reject(new Error(res.data.message || '更新用户信息失败'));
                    }
                }
            },
            fail: (err) => {
                reject(err);
            }
        });
    });
};

export const getChatIds = (type) => {
  return request({
    url: `${getBaseUrl()}/ai/history/getChatIds/${type}`,
    method: 'GET',
    header: {
      'Authorization': 'Bearer ' + uni.getStorageSync('token')
    }
  });
};


export const getChatHistory = (type, chatId = '') => {
  const url = chatId
    ? `${getBaseUrl()}/ai/history/${type}/${chatId}`
    : `${getBaseUrl()}/ai/history/${type}`;
  return request({
    url,
    method: 'GET',
    header: {
      'Authorization': 'Bearer ' + uni.getStorageSync('token')
    }
  });
};

export const sendGeneralMessage = (message, assistantType, conversationId = '') => {
  return request({
    url: `${getBaseUrl()}/postgraduate/assist`,
    method: 'POST',
    header: {
      'Authorization': 'Bearer ' + uni.getStorageSync('token')
    },
    data: { message, assistantType, conversationId }
  }, 0, 3); // 最多重试3次
};

export const sendAnalysisMessage = (message, conversationId = '') => {
  return request({
    url: `${getBaseUrl()}/postgraduate/analysis`,
    method: 'POST',
    header: {
      'Authorization': 'Bearer ' + uni.getStorageSync('token')
    },
    data: { message, assistantType: 'QUESTION_ANALYSIS', conversationId }
  }, 0, 3); // 最多重试3次
};

// 为请求添加超时处理
const withTimeout = (promise, timeout = 300000) => {
  return new Promise((resolve, reject) => {
    const timeoutId = setTimeout(() => {
      reject(new Error('请求超时'));
    }, timeout);
    
    promise.then(
      (value) => {
        clearTimeout(timeoutId);
        resolve(value);
      },
      (error) => {
        clearTimeout(timeoutId);
        reject(error);
      }
    );
  });
};

/**
 * 获取所有学科
 * @returns {Promise} - 返回Promise对象
 */
export const getAllSubjects = () => {
  return request({
    url: `${getBaseUrl()}/chapter/getAllSubjects`,
    method: 'GET',
    header: {
      'Authorization': 'Bearer ' + uni.getStorageSync('token')
    }
  });
};

/**
 * 根据学科ID获取章节列表
 * @param {string|number} subjectId - 学科ID
 * @returns {Promise} - 返回Promise对象
 */
export const getChaptersBySubjectId = (subjectId) => {
  return request({
    url: `${getBaseUrl()}/chapter/getChaptersBySubjectId/${subjectId}`,
    method: 'GET',
    header: {
      'Authorization': 'Bearer ' + uni.getStorageSync('token')
    }
  });
};
